class_name UnitFrog
extends UnitBase

@export var jump_speed: float = 180
var attack_cooldown_timer: float = 0
var start_jump_velocity_x: float = 0


func play_wander_animation():
	return


func process_approach(delta: float):
	if not attack_target: 
		states.transition("Wander")
		return
	
	if is_on_floor():
		animation_player.play("idle")
		velocity = Vector2.ZERO
		
		attack_cooldown_timer -= delta
		if attack_cooldown_timer <= 0:
			var target_dir = sign(attack_target.global_position.x - global_position.x)
			var x_speed = target_dir * approach_speed
			start_jump_velocity_x = x_speed
			var y_speed = -jump_speed
			velocity = Vector2(x_speed, y_speed)
			
			attack_cooldown_timer = unit_data.config.main_attack_cooldown
	else:
		animation_player.play("jump")
		velocity.x = start_jump_velocity_x
		velocity.y += gravity * delta
	
	move_and_slide()
	

func process_wander(delta: float):
	if is_on_floor():
		animation_player.play("idle")
		velocity = Vector2.ZERO
	else:
		animation_player.play("jump")
		velocity.x = start_jump_velocity_x
		velocity.y += gravity * delta
		move_and_slide()
	

func process_face():
	if velocity.x:
		view_root.scale.x = 1 if velocity.x > 0 else -1
		
		
func on_hit(source: Node2D):
	add_poison_buff_to_target(source)
		

func add_poison_buff_to_target(source: Node2D):
	var unit = source as UnitBase
	var unit_config = unit_data.config as UnitBaseConfig
	
	var poison_hit_rate = unit_config.poison_hit_rate 
	var is_hit = randf() < poison_hit_rate
	if is_hit and not unit.get_buff_by_name("buff_poison"):
		var buff_inst = unit.add_buff("buff_poison", self)
		
		buff_inst.duration = unit_config.poison_debuff_duration
		buff_inst.damage_per_second = unit_config.poison_damage_per_second
		buff_inst.sender = self
		buff_inst.start_buff()
	
